package ccnt.pvc.scudwaremobile.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class FileUtils {

	private final static String TAG = FileUtils.class.getName();
	
	/**
	 * 从Assets中的文件读取内容
	 * @param context context实例
	 * @param fileName 文件路径
	 * @return 文件内容
	 */
	public static String getFromAssets(Context context, String fileName) {
		try {
			 InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName)); 
			 BufferedReader bufReader = new BufferedReader(inputReader);
             String line="";
             String Result="";
             while((line = bufReader.readLine()) != null)
                 Result += line;
             return Result;
        } catch (Exception e) { 
             e.printStackTrace(); 
             return null;
        }
	}
	
	public static String downloadFileByUrl(String downloadUrl, String savePath, String fileName) {
		String filePath = null;
		OutputStream output = null;
		Log.d(TAG, "Download File: " + downloadUrl);
		try {
			URL url = new URL(downloadUrl);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
			String path = sdCardPath + "/" + savePath + "/" + fileName;
			File file = new File(path);
			if(file.exists()) {
				Log.e(TAG, "file exists: " + path);
				return null;
			}
			else {
				String dir = sdCardPath + "/" + savePath;  
				//新建文件夹  
				if(!new File(dir).exists()) {
					if(!new File(dir).mkdirs())
	                	return null;
				}
                file.createNewFile(); //新建文件  
                output = new FileOutputStream(file);  
                //读取大文件  
                InputStream input = conn.getInputStream();  
                byte[] buffer = new byte[4*1024];
                int count = 0;
                while((count = input.read(buffer)) != -1){  
                    output.write(buffer, 0, count);
                }  
                output.flush();  
                filePath = file.getAbsolutePath();
                Log.d(TAG, "Download Success: " + filePath);
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return filePath;
	}
}
